package com.jetpackframework.rxjetpack.observable;

import android.util.Log;

import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;

import com.jetpackframework.rxjetpack.DisposableHelper;
import com.jetpackframework.rxjetpack.Dispose;
import com.jetpackframework.rxjetpack.DisposeImpl;
import com.jetpackframework.rxjetpack.Observable;
import com.jetpackframework.rxjetpack.Observer;

public class ObservableLiveData<T> extends Observable<T> {
    private LifecycleOwner owner;
    private LiveData<T> liveData;

    public ObservableLiveData(LifecycleOwner owner, LiveData<T> liveData){
        this.owner = owner;
        this.liveData = liveData;
    }
    @Override
    public void subscribeActual(final Observer<? super T> observer) {
        liveData.observe(owner, new androidx.lifecycle.Observer<T>() {
            @Override
            public void onChanged(T t) {
                Dispose dispose = new DisposeImpl();
                observer.onSubscribe(dispose);
                if (!DisposableHelper.isDispose(dispose)) {
                    try {
                        observer.onNext(t);
                    } catch (Exception e) {
                        observer.onError(e);
                    }
                    observer.onComplete();
                }
            }
        });
    }
}
